<template>
  <div class="product-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品管理</span>
        </div>
      </template>
      <div class="content-body">
        <!-- 搜索和筛选区域 -->
        <div class="search-filter">
          <el-input 
            v-model="queryForm.productName" 
            placeholder="请输入商品名称搜索"
            style="width: 200px; margin-right: 10px;"
            prefix-icon="Search"
            clearable
          />
          <el-select v-model="queryForm.status" placeholder="选择状态" style="width: 120px; margin-right: 10px;">
            <el-option label="全部" value="" />
            <el-option label="上架" value="1" />
            <el-option label="下架" value="0" />
          </el-select>
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button type="primary" @click="handleAddProduct">新增商品</el-button>
        </div>
        
        <!-- 商品列表 -->
        <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="id" label="商品ID" width="80" />
          <el-table-column prop="productName" label="商品名称" width="150" />
          <el-table-column prop="productType" label="商品类型" width="120" />
          <el-table-column prop="beforePrice" label="原价" width="100" />
          <el-table-column prop="afterPrice" label="现价" width="100" />
          <el-table-column prop="balanceCount" label="库存" width="100" />
          <el-table-column label="是否上架" width="80">
            <template #default="{ row }">
              <el-switch v-model="row.status" active-value="1" inactive-value="0" @change="handleStatusChange(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="图片" width="120">
            <template #default="scope">
              <el-image 
                v-if="scope.row.image"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                style="width: 40px; height: 40px; border-radius: 4px;"
              />
              <span v-else>暂无</span>
            </template>
          </el-table-column>
          <el-table-column prop="introduction" label="介绍" width="200" :show-overflow-tooltip="true" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditProduct(scope.row)">编辑</el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDeleteProduct(scope.row.id)"
                v-if="!isDeleting"
              >
                删除
              </el-button>
              <el-button type="primary" size="small" @click="handleAddStock(scope.row)">补货</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination" style="margin-top: 20px; text-align: right;">
          <el-pagination 
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑商品弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      @close="resetForm"
    >
      <el-form 
        ref="productFormRef" 
        :model="productForm" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="productForm.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品类型" prop="productType">
          <el-select v-model="productForm.productType" placeholder="请选择商品类型">
            <el-option label="球拍" value="球拍" />
            <el-option label="网球" value="网球" />
            <el-option label="服装" value="服装" />
            <el-option label="配件" value="配件" />
            <el-option label="鞋类" value="鞋类" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="原价" prop="beforePrice">
          <el-input-number 
            v-model="productForm.beforePrice" 
            :min="0" 
            :step="0.01" 
            placeholder="请输入原价"
          />
        </el-form-item>
        <el-form-item label="现价" prop="afterPrice">
          <el-input-number 
            v-model="productForm.afterPrice" 
            :min="0" 
            :step="0.01" 
            placeholder="请输入现价"
          />
        </el-form-item>
        <el-form-item label="商品介绍" prop="introduction">
          <el-input v-model="productForm.introduction" type="textarea" placeholder="请输入商品介绍" />
        </el-form-item>
        <el-form-item label="数量" prop="balanceCount">
          <el-input-number 
            v-model="productForm.balanceCount" 
            :min="0" 
            :step="1" 
            placeholder="请输入数量"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <div v-if="!productForm.image">
            <el-upload
              class="image-upload"
              drag
              :action="uploadUrl"
              :headers="uploadHeaders"
              :on-success="handleImageUploadSuccess"
              :on-error="handleImageUploadError"
              :before-upload="beforeImageUpload"
              :show-file-list="false"
              accept="image/*"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽图片到此处或 <em>点击上传</em>
              </div>
            </el-upload>
          </div>
          <div v-else class="image-preview">
            <img 
              :src="productForm.image" 
              alt="商品图片" 
              class="uploaded-image"
            >
            <el-button 
              type="danger" 
              size="small" 
              @click.stop="removeImage"
            >
              删除图片
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, ElSwitch, ElImage } from 'element-plus'
import { Search, Upload, UploadFilled } from '@element-plus/icons-vue'
import { productList, productAdd, productDelete, productUpdate,productStatusUpdate,productAddStock } from '@/request/product.js' 

// 上传配置
const uploadUrl = '/api/system/file/uploadFile'
const uploadHeaders = {
  Authorization: localStorage.getItem('token') || ''
}

const queryForm = ref({
  pageNum: 1,
  pageSize: 10,
  name: '',
  status: ''
})
// 搜索条件

const isDeleting = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增商品')
const productFormRef = ref(null)
const editingProductId = ref(null)

const tableData = ref([])
const total = ref(0)


const getList=()=>{
  productList(queryForm.value).then(res=>{
    tableData.value = res.records
    total.value = res.total
    
    // 处理图片URL，确保显示正确
    tableData.value.forEach(item => {
      if (item.image) {
        // 检查是否已经包含/api前缀
        if (!item.image.startsWith('/api') && !item.image.startsWith('http')) {
          // 添加/api前缀
          item.image = '/api' + item.image
        }
      }
    })
  })
}
getList()

// 商品表单
const productForm = reactive({
  productName: '',
  productType: '',
  beforePrice: null,
  afterPrice: null,
  introduction: '',
  image: '',
  balanceCount: null,
  status: ''
})


// 表单验证规则
const formRules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '商品名称长度应在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  productType: [
    { required: true, message: '请选择商品类型', trigger: 'change' }
  ],
  beforePrice: [
    { required: true, message: '请输入原价', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' }
  ],
  afterPrice: [
    { required: true, message: '请输入现价', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' }
  ],
  introduction: [
    { required: true, message: '请输入商品介绍', trigger: 'blur' },
    { min: 10, max: 50, message: '商品介绍长度应在 10 到 50 个字符之间', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传商品图片', trigger: 'change' }
  ],
  balanceCount: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '数量不能为负数', trigger: 'blur' },
    { type: 'integer', message: '数量必须为整数', trigger: 'blur' }
  ]
}

// 重置表单
const resetForm = () => {
  if (productFormRef.value) {
    productFormRef.value.resetFields()
  }
  editingProductId.value = null
  Object.keys(productForm).forEach(key => {
    if (key === 'beforePrice' || key === 'afterPrice' || key === 'balanceCount') {
      productForm[key] = null
    } else {
      productForm[key] = ''
    }
  })
}

// 删除图片
const removeImage = () => {
  productForm.image = ''
}


// 新增商品
const handleAddProduct = () => {
  dialogTitle.value = '新增商品'
  resetForm()
  dialogVisible.value = true
}

// 编辑商品
const handleEditProduct = (product) => {
  dialogTitle.value = '编辑商品'
  editingProductId.value = product.id
  // 复制商品数据到表单，并转换数字类型字段
  Object.keys(productForm).forEach(key => {
    if (key === 'beforePrice' || key === 'afterPrice' || key === 'balanceCount') {
      // 将字符串转换为数字
      productForm[key] = Number(product[key]) || 0
    } else if (key === 'image') {
      // 处理图片URL，确保格式正确
      if (product[key]) {
        // 检查是否已经包含/api前缀
        if (product[key].startsWith('/api')) {
          productForm[key] = product[key]
        } else {
          // 检查是否是完整的URL (以http开头)
          if (product[key].startsWith('http://') || product[key].startsWith('https://')) {
            productForm[key] = product[key]
          } else {
            // 添加/api前缀
            productForm[key] = '/api' + product[key]
          }
        }
      } else {
        productForm[key] = ''
      }
    } else {
      productForm[key] = product[key]
    }
  })
  dialogVisible.value = true
}

// 图片上传成功
const handleImageUploadSuccess = (response, file) => {
  if (response && response.data) {
    // 检查响应中的数据是否已经包含/api前缀
    if (typeof response.data === 'string' && !response.data.startsWith('/api') && !response.data.startsWith('http')) {
      // 只在需要时添加/api前缀
      productForm.image = '/api' + response.data
    } else {
      productForm.image = response.data
    }
  } else {
    // 创建本地URL用于预览，但实际提交时会进行检查
    productForm.image = URL.createObjectURL(file.raw)
  }
  ElMessage.success('图片上传成功')
}

// 图片上传失败
const handleImageUploadError = (error) => {
  ElMessage.error('图片上传失败')
}

// 图片上传前检查
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

// 提交表单
const handleSubmit = () => {
  productFormRef.value.validate((valid) => {
    if (valid) {
      // 提交时检查
      if (!productForm.image) {
        ElMessage.error('请上传商品图片！')
        return
      }
      
      // 创建提交表单数据的副本，避免直接修改原表单
      const submitData = { ...productForm }
      
      // 处理图片URL格式
      if (submitData.image) {
        // 如果URL以/api开头，移除前缀
        if (submitData.image.startsWith('/api')) {
          submitData.image = submitData.image.substring(4)
        }
        // 如果是完整的URL (以http开头)，需要特殊处理
        else if (submitData.image.startsWith('http://') || submitData.image.startsWith('https://')) {
          // 如果是本地预览URL (blob:)，则忽略（不应该在提交时出现）
          if (submitData.image.startsWith('blob:')) {
            ElMessage.error('图片尚未上传完成，请稍候重试！')
            return
          }
        }
      }
      
      if (editingProductId.value) {
        // 编辑模式
        submitData.id = editingProductId.value
        productUpdate(submitData).then(res=>{
          ElMessage.success('商品更新成功')
          dialogVisible.value = false
          resetForm()
          getList()
        }).catch(() => {
          ElMessage.error('商品更新失败')
        })
      } else {
        // 新增模式
        submitData.status = '1' // 默认上架状态
        productAdd(submitData).then(res=>{
          ElMessage.success('商品添加成功')
          dialogVisible.value = false
          resetForm()
          getList()
        }).catch(() => {
          ElMessage.error('商品添加失败')
        })
      }
    }
  })
}


// 切换商品状态
const handleStatusChange = (product) => {
  const status = product.status === '1' ? '1' : '0'
  productStatusUpdate(product.id, status).then(res=>{
    ElMessage.success(`商品${status === '1' ? '上架' : '下架'}成功`)
    getList()
  })
}

// 删除商品
const handleDeleteProduct = (id) => {
  ElMessageBox.confirm('确定要删除这个商品吗？删除后无法恢复。', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    isDeleting.value = true
    productDelete(id).then(res=>{
      ElMessage.success('商品删除成功')
      isDeleting.value = false
      getList()
    })
  }).catch(() => {
    
  })
}

// 分页相关方法
const handleSizeChange = (size) => {
  queryForm.value.pageSize = size
  getList()
}

const handleCurrentChange = (current) => {
  queryForm.value.pageNum = current
  getList()
}

// 补货功能
const handleAddStock = (product) => {
  ElMessageBox.prompt(
    `当前库存: ${product.balanceCount || 0}，请输入要补充的数量`,
    '商品补货',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^\d+$/,
      inputErrorMessage: '请输入正整数',
      inputValue: '0'
    }
  ).then(({ value }) => {
    const addCount = parseInt(value)
    if (addCount <= 0) {
      ElMessage.error('补货数量必须大于0')
      return
    }
    
    // 调用更新库存的API
    productAddStock(product.id, addCount).then(res => {
      ElMessage.success('补货成功')
      getList() // 重新获取列表数据以更新库存显示
    }).catch(() => {
      ElMessage.error('补货失败，请重试')
    })
  
  }).catch(() => {
    
  })
}
</script>

<style scoped>


.content-body {
  padding-top: 10px;
}

.search-filter {
  display: flex;
  align-items: center;
}

.image-preview {
  margin-top: 10px;
}

.image-preview h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #606266;
}

/* 限制上传图片的大小 */
.uploaded-image {
  max-width: 300px;
  max-height: 200px;
  border: 1px solid #ddd;
  padding: 5px;
  border-radius: 4px;
}

.image-upload {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>